# -*- coding: utf-8 -*-

"""
    http://projecteuler.net/problem=67
    
    PROBLEM

    By starting at the top of the triangle below and moving to adjacent numbers
    on the row below, the maximum total from top to bottom is 23.

    3
    7 4
    2 4 6
    8 5 9 3

    That is, 3 + 7 + 4 + 9 = 23.

    Find the maximum total from top to bottom in triangle.txt (right click and
    'Save Link/Target As...'), a 15K text file containing a triangle with
    one-hundred rows.

    NOTE: This is a much more difficult version of Problem 18. It is not
    possible to try every route to solve this problem, as there are 299
    altogether! If you could check one trillion (1012) routes every second it
    would take over twenty billion years to check them all. There is an
    efficient algorithm to solve it. ;o)
    
    
    NOTES
    Uses same algorithm as Problem #18
    
    
    REFERENCES
    
    
    PERFORMANCE
    time <function solution at 0x7fb476975848>: 0.022081 s

"""
#
# Import
#
import time
from os.path import join as pathjoin, dirname


#
# Globals / Constants
#
data_file = '067_data.txt'
this_dir = dirname(__file__)

def timeit(f):
    def timer():
        t0 = time.time()
        returned = f()
        print "time %s: %.6f s" % (f, time.time() - t0)
        return returned
    return timer

def assert_match(value, expected):
    assert value == expected, "value %s != expected %s" % (
        value, expected)
    
def read_file(path):
    f = open(path)
    content = f.read()
    f.close()
    return content
    


#
# Test Case / Solution
#
@timeit    
def test_case():
    expected = 23
    triangle = """
    3
    7 4
    2 4 6
    8 5 9 3
"""

    graph = parse_triangle(triangle)
    assert_match(len(graph), 4)
    assert_match(len(graph[0]), 1)
    assert_match(len(graph[3]), 4)
    assert_match(graph[0][0], 3)
    assert_match(graph[2][1], 4)
    
    scored_graph = score_graph(graph)
    assert_match(len(scored_graph), 4)
    assert_match(len(scored_graph[0]), 1)
    assert_match(len(scored_graph[3]), 4)
    
    path = walk_scored_graph(scored_graph)
    values = nodes_to_values(path, graph)
    total = sum(values)
    
    assert_match(scored_graph[0][0], expected)    
    assert_match(total, expected)
    print "test case passed!"

@timeit
def solution():
    data = read_file(pathjoin(this_dir, data_file))
    graph = parse_triangle(data)
    scored_graph = score_graph(graph)
    path = walk_scored_graph(scored_graph)
    values = nodes_to_values(path, graph)
    #print "path:", path
    
    summa = sum(values)
    assert_match(summa, scored_graph[0][0])
    return summa
        

#
# Support Code
#
def parse_triangle(source):
    """returns a dict of dicts where keys are row numbers (y) and values are
    dicts where key is col-num x and value is value"""
    graph = {}
    lines = source.strip().split("\n")
    
    for y in xrange(len(lines)):
        line = lines[y]
        cols = line.strip().split(" ")
        graph[y] = dict()
        
        for x in xrange(len(cols)):
            graph[y][x] = int(cols[x])
        
    return graph


def score_graph(graph):
    """returns a graph with nodes scored to facilitate pathfinding"""
    return sum_up_maxes(graph)

    
def sum_up_maxes(graph):
    """a graph scoring algorithm that starts at the bottom of the triangle
    tree and takes the max score of two child nodes and adds that to the parent
    rolling scores up the graph"""
    scored_graph = {}
    last_row = len(graph) - 1
    scored_graph[last_row] = dict(graph[last_row])
    
    y = last_row - 1
    
    while y >= 0:
        scored_graph[y] = dict()
        
        for x in graph[y]:
            scored_graph[y][x] = get_node_score(graph, scored_graph, y, x)
            
        y -= 1
            
    return scored_graph


def get_node_score(graph, scored_graph, y, x):
    """take the value of most valuable child node (from scored graph) of node
    at y,x and add that to node's score (from graph)"""
    self_score = graph[y][x]
    
    children = get_children(graph, y, x)
    scores = nodes_to_values(children, scored_graph)
    scored_children = zip(scores, children)
    max_child_score = sorted(scored_children)[-1][0]
    
    return max_child_score + self_score


def walk_scored_graph(scored_graph):
    route = [(0,0)]
    end_row = len(scored_graph) - 1
    y = 0
    
    while y < end_row:
        next_pt = choose_next_step(route, scored_graph)
        route.append(next_pt)
        y += 1
        
    return route


def choose_next_step(route, scored_graph):
    y, x = route[-1]
    
    children = get_children(scored_graph, y, x)
    child_scores = nodes_to_values(children, scored_graph)
    scored_children = zip(child_scores, children)
    
    max_child = sorted(scored_children)[-1]
    next_step = max_child[1]        
    return next_step


def get_children(grid, y, x):
    """returns a list of (y,x) tuples for all immediate children of node at
    y, x"""
    children = []
    below = y + 1
    left, right = x, x+1
    
    if below in grid and left in grid[below]:
        children.append((below, left))
        
    if below in grid and right in grid[below]:
        children.append((below, right))
        
    return children

    
def nodes_to_values(path, grid):
    """path is a list of tuples (y,x) in path"""
    values = []
    
    for y, x in path:
        values.append(grid[y][x])
        
    return values
    
    

#
# Additional Tests
#
def test_read_file():
    content = read_file(pathjoin(this_dir, data_file))
    #print content
    assert len(content) > 10000, "was file read properly?"
    print "test_read_file passed!"



#
# Main
#
if __name__ == '__main__':
    test_read_file()
    test_case()
    print solution()
    